package com.yygo.webapp.controller;

import com.yygo.model.Feedback;
import com.yygo.model.LoanRequest;
import com.yygo.service.FeedbackManager;
import com.yygo.service.LoanRequestManager;
import org.apache.commons.lang.StringUtils;
import org.appfuse.service.GenericManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Controller
@RequestMapping("/requestfeedback*")
public class FeedbackRequesstController extends BaseFormController {

    @Autowired
    private FeedbackManager feedbackManager;

    private LoanRequestManager loanRequestManager;

    @Autowired
    public void setLoanRequestManager(@Qualifier("loanRequestManager") LoanRequestManager loanRequestManager) {
        this.loanRequestManager = loanRequestManager;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(Feedback feedback, BindingResult errors, HttpServletRequest request,
                           HttpServletResponse response)
    throws Exception {

        if (validator != null) { // validator is null during testing
            validator.validate(feedback, errors);

            if (errors.hasErrors()) {
                return "redirect:/feedbacks?reqId=" + feedback.getReqId();
            }
        }
        log.debug("entering 'onSubmit' method...");

        Locale locale = request.getLocale();

        LoanRequest loanRequest = loanRequestManager.get(feedback.getReqId());
        feedback.setReqStatus(loanRequest.getStatus());
        feedback.setLoanRequest(loanRequest);
        //loanRequest.getFeedbackList().add(feedback);
        //loanRequestManager.save(loanRequest);

        feedback.setLoanRequest(loanRequest);
        feedback.setReqStatus(loanRequest.getStatus());
        feedbackManager.save(feedback);

        String key = "feedback.added";
        saveMessage(request, getText(key, locale));

        return "redirect:/feedbacks?reqId=" + loanRequest.getId();
    }
}
